package com.kotlin.demo

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class Test03GlobalScope {
    fun globalScopeTest() {
        println("start")
        GlobalScope.launch {
            launch {
                delay(400)
                println("launchA")
            }
            launch {
                delay(300)
                println("launchB")
            }
            println("GlobalScope")
        }
        println("end")
        Thread.sleep(500)//start end GlobalScope launchB launchA
    }

    fun runBlockingTest() {
        println("start")
        runBlocking {
            launch {
                repeat(3) {
                    delay(100)
                    println("launchA - $it")
                }
            }
            launch {
                repeat(3) {
                    delay(100)
                    println("launchB - $it [${Thread.currentThread().name}]")
                }
            }
            GlobalScope.launch {
                repeat(3) {
                    delay(120)
                    println("GlobalScope - $it [${Thread.currentThread().name}]")
                }
            }
        }
        println("end")
    }

    fun coroutineScopeTest() = runBlocking {
        launch {
            delay(1000)
            println("Task from runBlocking")
        }
        coroutineScope {
            launch {
                delay(2000)
                println("Task from nested launch")
            }
            delay(5000)
            println("Task from coroutine scope")
        }
        coroutineScope {
            launch {
                delay(2000)
                println("b")
            }
            delay(5000)
            println("b")
        }
        println("Coroutine scope is over")
    }


}